import enquireJs from 'enquire.js'
import _ from 'lodash'

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : hour <= 11 ? '上午好' : hour <= 13 ? '中午好' : hour < 20 ? '下午好' : '晚上好'
}

export function welcome() {
  const arr = ['休息一会儿吧', '准备吃什么呢?', '要不要打一把 DOTA', '我猜你可能累了']
  const index = Math.floor(Math.random() * arr.length)
  return arr[index]
}

/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  const event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

export function isIE() {
  const bw = window.navigator.userAgent
  const compare = (s) => bw.indexOf(s) >= 0
  const ie11 = (() => 'ActiveXObject' in window)()
  return compare('MSIE') || ie11
}

/**
 * Remove loading animate
 * @param id parent element id or class
 * @param timeout
 */
export function removeLoadingAnimate(id = '', timeout = 1500) {
  if (id === '') {
    return
  }
  setTimeout(() => {
    document.body.removeChild(document.getElementById(id))
  }, timeout)
}

/**
 * Remove an item from an array.
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function isRegExp(v) {
  return _toString.call(v) === '[object RegExp]'
}

/*
 * 获取浏览器版本信息
 */
export function getBrowerInfo() {
  const userAgent = window.navigator.userAgent.toLowerCase()
  let browserType = ''
  let browserVersion = ''
  // 浏览器类型-IE
  if (userAgent.match(/msie/) != null || userAgent.match(/trident/) != null) {
    browserType = 'ie'
    browserVersion = getIeVersion()
  } else if (window.opera || (userAgent.indexOf('opr') > 0)) {
    // 欧朋
    browserType = 'opr'
    browserVersion = getOperaVersion(userAgent)
  } else if (userAgent.indexOf('ubrowser') > 0) {
    browserType = 'uc'
    browserVersion = userAgent.match(/ubrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('bidubrowser') > 0) {
    // 百度
    browserType = 'baidu'
    browserVersion = userAgent.match(/bidubrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('metasr') > 0 || userAgent.indexOf('se 2.x') > 0) {
    // 搜狗
    browserType = 'metasr'
    // browserVersion =  userAgent.match(/metasr\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('tencenttraveler') > 0) {
    browserType = 'qq'
    browserVersion = userAgent.match(/tencenttraveler\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('qqbrowser') > 0) {
    browserType = 'qq'
    browserVersion = userAgent.match(/qqbrowser\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('maxthon') > 0) {
    // 遨游
    browserType = 'maxthon'
    browserVersion = userAgent.match(/maxthon\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('firefox') > 0) {
    // 火狐
    browserType = 'firefox'
    browserVersion = userAgent.match(/firefox\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('edge') > 0) {
    // edge
    browserType = 'edge'
    browserVersion = userAgent.match(/edge\/([\d.]+)/)[1]
  } else if (userAgent.indexOf('chrome') > 0) {
    // 谷歌/360
    if (validate360('type', 'application/x360mmplugin')) {
      browserType = '360'
      // browserVersion =  userAgent.match(/chrome\/([\d.]+)/)[1]
    } else {
      browserType = 'chrome'
      browserVersion = userAgent.match(/chrome\/([\d.]+)/)[1]
    }
  } else if (userAgent.indexOf('Safari') > -1) {
    // 苹果
    browserType = 'safari'
    browserVersion = userAgent.match(/version\/([\d.]+)/)[1]
  } else {
    browserType = 'other'
  }
  const browser = {}
  browser.browserType = browserType
  browser.browserVersion = browserVersion
  return browser
}

/*
 * 判断是否为360浏览器
 */
export function validate360(option, value) {
  const mimeTypes = window.navigator.mimeTypes
  for (const mt in mimeTypes) {
    console.log(mimeTypes[mt][option])
    if (mimeTypes[mt][option] === value) {
      return true
    }
  }
  return false
}

/*
 * 获取IE浏览器版本
 */
export function getIeVersion() {
  const IEMode = document.documentMode
  const rMsie = /(msie\s|trident.*rv:)([\w.]+)/
  const ma = window.navigator.userAgent.toLowerCase()
  const match = rMsie.exec(ma)
  try {
    return match[2]
  } catch (e) {
    return IEMode
  }
}

/*
 * 获取oper浏览器版本
 */
export function getOperaVersion(userAgent) {
  try {
    if (window.opera) {
      return userAgent.match(/opera.([\d.]+)/)[1]
    } else if (userAgent.indexOf('opr') > 0) {
      return userAgent.match(/opr\/([\d.]+)/)[1]
    }
  } catch (e) {
    return 0
  }
}

export function uuid() {
  const s = []
  const hexDigits = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }
  s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

export function formtojson(params) {
  var values = {}
  for (var item in params) {
    values[item] = params[item]
  }
  return values
}

export function loop(data, key, callback) {
  data.forEach((item, index, arr) => {
    if (item.key === key) {
      return callback(item, index, arr)
    }
    if (item.children) {
      return loop(item.children, key, callback)
    }
  })
}

export function loopParentKey(data, value, keys) {
  let flag = false
  data.forEach((item) => {
    let itemFlag = false
    if (item.title && item.title.indexOf(value) > -1) {
      itemFlag = true
    }
    if (item.children) {
      const childFlag = loopParentKey(item.children, value, keys)
      if (childFlag) {
        itemFlag = true
      }
    }
    if (itemFlag) {
      flag = true
      keys.push(item.key)
    }
  })
  return flag
}

export function loopLeafKey(data, keys) {
  // 获取所有选中数据
  data.forEach((item) => {
    if (item.children) {
      return loopLeafKey(item.children, keys)
    } else {
      keys.push(item.key)
    }
  })
}

export function loopKey(data, keys) {
  // 获取所有选中数据
  data.forEach((item) => {
    keys.push(item.key)
    if (item.children) {
      return loopKey(item.children, keys)
    }
  })
}

export function loopExpandCheck(data, checkedKeys, expandedKeys) {
  data.forEach((item) => {
    expandedKeys.push(item.key)
    if (item.children) {
      return loopExpandCheck(item.children, checkedKeys, expandedKeys)
    } else {
      checkedKeys.push(item.key)
    }
  })
}

/***
 * 时间搓 格式化
 */
export function formatDate(datetime) {
  const date = new Date(datetime)// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const year = date.getFullYear()
  const month = ('0' + (date.getMonth() + 1)).slice(-2)
  const sdate = ('0' + date.getDate()).slice(-2)
  const hour = ('0' + date.getHours()).slice(-2)
  const minute = ('0' + date.getMinutes()).slice(-2)
  const second = ('0' + date.getSeconds()).slice(-2)
  // 拼接
  var result = year + '-' + month + '-' + sdate + ' ' + hour + ':' + minute + ':' + second
  // 返回
  return result
}

/**
 * 下划线转驼峰
 * @param string
 * @returns {*}
 */
export function underLine2CamelCase(string) {
  return string.replace(/_([a-z])/g, function (all, letter) {
    return letter.toUpperCase();
  });
}

/**
 * 简单实现防抖方法
 *
 * 防抖(debounce)函数在第一次触发给定的函数时，不立即执行函数，而是给出一个期限值(delay)，比如100ms。
 * 如果100ms内再次执行函数，就重新开始计时，直到计时结束后再真正执行函数。
 * 这样做的好处是如果短时间内大量触发同一事件，只会执行一次函数。
 *
 * @param fn 要防抖的函数
 * @param delay 防抖的毫秒数
 * @returns {Function}
 */
export function simpleDebounce(fn, delay = 100) {
  let timer = null
  return function () {
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}

export function enquireScreen(call) {
  const handler = {
    match: function () {
      call && call(true)
    },
    unmatch: function () {
      call && call(false)
    }
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}

export function isDef(v) {
  return v !== undefined && v !== null
}

export function isEmptyStr(value) {
  let str = ""
  if (value == null || value == undefined) {
    str = value
  } else {
    str = value + ""
  }
  if (str == null || str == 'null' || str == undefined || str == 'undefined' || str.match(/^[\s]*$/)) {
    return true;
  } else {
    return false;
  }

}

/**
 * @description   判断数据是否为网址(URL),请传入满足http标准协议的链接
 * @param {String} str_data 待校验的数据
 * @param {Boolean} flag 是否使用严格模式,默认为false
 * @returns {Boolean}, true:是网址
 **/
export function isUrl(str_data, flag) {
  str_data = str_data || String(this);
  flag = flag || false;
  let regular = /^\b(((https?|ftp):\/\/)?[-a-z0-9]+(\.[-a-z0-9]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|((25[0-5])|(2[0-4]\d)|(1\d\d)|([1-9]\d)|\d))\b(\/[-a-z0-9_:@&?=+,.!/~%$]*)?)$/i
  let regular2 = /^((https?|ftp):\/\/)(www\.)?\S{0,30}\.\S+$/i

  if (regular2.test(str_data) && !flag) {
    return true;
  } else if (regular.test(str_data) && flag) {
    return true;
  } else {
    return false;
  }
}

/***获取url上的参数 */
export function getQueryString(name) {
  const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  const search = window.location.search.split('?')[1] || '';
  if (search) {
    const r = search.match(reg) || [];
    return r[2]
  } else {
    return null
  }

}

/***格式化级联数据，去除空数组children */
export function formatCascader(data) {
  data.forEach((item) => {
    if (!item.children) {
      delete item.children
    } else {
      formatCascader(item.children)
    }
  })
  return data
}

/***用于下拉框级联数据的还原*/
export function findCascaderOne(findKey, data, keyName) {
  let filterdata = filterCascader(findKey, data, keyName)
  let result = [];
  fn(filterdata);

  function fn(obj) {
    obj.forEach(item => {
      if (item[keyName]) {
        result.push(item[keyName]);
      }
      if (item.children) {
        fn(item.children);
      }
    })

  }

  return result
}

function filterCascader(findKey, data, keyName) {
  let result = _.filter(data, function (item) {
    if (item[keyName] === findKey) {
      return true;
    } else {
      let filterItem = filterCascader(findKey, item.children, keyName);
      if (filterItem.length > 0) {
        item.children = filterItem;
        return true;
      } else {
        return false;
      }
    }
  })
  return result
}

const _toString = Object.prototype.toString
